//
//  LHComposeController.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/19.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import SVProgressHUD

class LHComposeController: UIViewController, UITextViewDelegate {
    
    //MARK: --自定义发送按钮
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        button.frame.size = CGSize(width: 45, height: 30)
        
        return button
    }()
    
    //MARK: --自定义titleView
    private lazy var titleView: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        
        if let name = LHUserAccountModel.sharedUserAccount.userAccount?.name {
            let title = "发微博\n\(name)"
            let range = (title as NSString).rangeOfString(name)
            
            //创建富文本
            let attributedStr = NSMutableAttributedString(string: title)
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range:range)
            attributedStr.addAttribute(NSFontAttributeName, value:UIFont.systemFontOfSize(14), range:range)
            label.attributedText = attributedStr
        
        } else {
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        return label
    }()
    
    //MARK: --自定义textView
    private lazy var composeTextView: LHComposeTextView = {
        let view = LHComposeTextView()
        view.placeHolder = "请输入内容"
        view.alwaysBounceVertical = true
        view.delegate = self
        return view
    }()
    
    //MARK: --自定义toolBar
    private lazy var composeToolBar: LHComposeToolBar = {
        let toolBar = LHComposeToolBar(frame: CGRectZero)
        return toolBar
    }()
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        //监听键盘位置的改变，目的是是toolBar随键盘弹起
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.bottom.equalTo(composeToolBar.snp_top)
            make.trailing.equalTo(view)
        }
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view)
            make.bottom.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
        //MARK: --实现toolBar的闭包
        composeToolBar.didSelectedButtonClosure = {[weak self] (type: LHComposeToolBarType) -> () in
            
            switch type {
            case .Picture:
                print("Picture")
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                print("Emoticon")
            case .Add:
                print("add")
            
            }
        }
    }
    
    
    
    
    //MARK: --设置navigationBar
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        rightButton.enabled = false
        navigationItem.titleView = titleView
        
        
    }

    //MARK: --响应点击事件
    @objc private func cancelAction() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: --实现发送按钮的点击事件
    @objc private func sendAction() {
        
        let accessToken = LHUserAccountModel.sharedUserAccount.accessToken!
        let status = composeTextView.text!
        
        SVProgressHUD.show()
        
        LHNetWorkTools.sharedTools.update(accessToken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络请求失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
    }
    
    //MARK: --监听键盘位置的改变
    @objc private func keyboardChageFrame(noti: NSNotification) {
        
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
//        print(keyboardFrame)
        
        let keyboardDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
//        print(keyboardDuration)
        
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)
        }
        
        UIView.animateWithDuration(keyboardDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    //监听文本框的输入，激活右侧按钮
    func textViewDidChange(textView: UITextView) {
        rightButton.enabled = textView.hasText()
    }
    
    
    //键盘收起的方法
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
//        view.endEditing(true)
    }
    
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}
